package com.nd.android.u.ui.widge;

import ims.manager.IMSStateManager;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.common.android.utils.DisplayUtil;
import com.common.android.utils.audio.TalkPopWindow;
import com.nd.android.u.allCommonUtils.ToastUtils;
import com.nd.android.u.controller.ChatConst;
import com.nd.android.u.controller.MessageConst.MessageCommonState;
import com.nd.android.u.controller.MessageConst.MessageState;
import com.nd.android.u.controller.factory.MessageLongClickMenuFactory;
import com.nd.android.u.controller.innerInterface.IChatListItem;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.controller.observer.MessageDispatcher;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.chatUiUtils.AudioQuenePlayManager;
import com.product.android.business.ApplicationVariable;
import com.product.android.ui.widget.AnimImageView;

/**
 * ClassName:ChatListItemView_Audio
 * Function: 聊天界面语音消息控件：具体实现在父类
 * Reason:	 messageview的子控件，用于控制语音文件的显示、上传、下载以及播放状态
 * 
 * @author   cb
 * @version  
 * @since    Ver 1.2
 * @Date	 2013	2013-8-8		上午10:10:24
 *
 * @see 	 
 */
public class ChatListItemView_Audio extends LinearLayout implements IChatListItem{//ChatListItemView_Audio_Common{

	public final static int MIN_LENGTH=80;

    public static final int HIGHER_METRICS = 440;
    public static final int LOWER_METRICS = 120;
	
	protected Context mContext;
	

	protected IMessageDisplay mMessage;

	protected double mLenPerSecond;
	
	protected int mMaxLen;
	protected int mMinLen;
	
//	protected ImageView mIvAudioLine;

    protected GifImageView mGifAudioLine;

    protected  GifDrawable mGifDrawable;
	
	/**
	 * ChatListItemView_Audio.构造方法
	 * <br>Created 2014-9-12 上午11:29:03
	 * @param context
	 */
	public ChatListItemView_Audio(Context context) {
		super(context);
		initView(context);
	}
	
	/**
	 * ChatListItemView_Audio.构造方法
	 * <br>Created 2014-9-12 上午11:29:05
	 * @param context
	 * @param attrs
	 */
	public ChatListItemView_Audio(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}
	
	private void initView(Context context) {
		LayoutInflater.from(context).inflate(R.layout.chat_list_item_audio, this);
		mContext=context;
		mMinLen=DisplayUtil.dip2px(mContext, MIN_LENGTH);
		mMaxLen=(int) (ApplicationVariable.INSTANCE.displayMetrics.widthPixels*0.6-DisplayUtil.dip2px(mContext, 50));
		mLenPerSecond=1f*(mMaxLen-mMinLen)/TalkPopWindow.MAX_RECORD_TIME;
//		mAnimImageView=(AnimImageView)findViewById(R.id.animImageView);
//		llAnimview=(LinearLayout) findViewById(R.id.llAnimview);
//		mIvAudioLine = (ImageView)findViewById(R.id.iv_audio_line);
        mGifAudioLine = (GifImageView)findViewById(R.id.gif_audio_line);
		
	}
	
	/**
	 * 设置数据
	 * 
	 * <br>Created 2014-10-17 下午5:11:19
	 * @param message 消息
	 * @author        :  HuangYK
	 */
	public void setData(IMessageDisplay message) {
        if(!message.equals(mMessage)){
            mMessage = message;
            initGifDrawable();
            stopGif();
        }
        // mAnimImageView.setMyTalk(message.isFromSelf());
        // mAnimImageView.setTag(message);

		this.setOnLongClickListener(mlistener);
		setOnClickListener(new AudioOnClickListener());
		int extraFlag = message.getExtraFlag();
		switch (extraFlag) {
		case MessageState.RECEIVED:
			// 刚收到的消息，开启下载
			mMessage.doDownload();
			break;
		case MessageState.SEND_SUCCESS:
			if (isAudioFileInvalid(message.getPath())) {
				Log.d("debug", "invalid audio file,set fail");
				// 语音文件无效，可能本地的语音文件损坏，从服务器上重新下载
				mMessage.doDownload();
			} else {
                if(mMessage.getCurrent() == AnimImageView.CURRENT_STOP){
                    stopGif();
                }
				// mAnimImageView.showState(message.current);
			}
			break;
		case MessageState.DOWNLOADING:
			// 正在下载中，判断uploaddownloadmanger里是否包含对应的URL
			break;
		case MessageState.DOWNLOAD_SUCCESS:
			if (isAudioFileInvalid(message.getPath())) {
				Log.d("debug", "invalid audio file,set fail");
				// 语音文件无效，认为下载失败
				MessageDispatcher.getInstance().notifyMessageStateChanged(
						mMessage, MessageState.DOWNLOAD_FAIL);
			} else {
                if(mMessage.getCurrent() == AnimImageView.CURRENT_STOP){
                    stopGif();
                }else{
                    // 如果是下载成功，并且不是自动开始播放的，需要执行动画
                    if (!mGifDrawable.isPlaying()) {
                        initGifDrawable();
                    }
                }
				// mAnimImageView.showState(message.current);
			}
			break;
		case MessageState.DOWNLOAD_FAIL:
		case MessageState.SEND_FAIL:
		case MessageState.UPLOAD_FAIL:
			// 在meesageview里已处理
            if(mMessage.getCurrent() == AnimImageView.CURRENT_STOP){
                stopGif();
            }
			break;
		default:
			break;
		}
	}

    /**
     * 初始化gif图片
     */
    private void initGifDrawable(){
        if (mGifDrawable != null) {
            mGifDrawable.recycle();
            mGifDrawable = null;
        }

        if (mMessage.isFromSelf()){
            mGifDrawable = getGifBg(R.drawable.bg_audio_line_to_gif);
            if (mGifDrawable == null) {
                mGifAudioLine.setBackgroundResource(R.drawable.bg_audio_line_to);
            } else {
                mGifAudioLine.setBackgroundDrawable(mGifDrawable);
            }
        }else{
            mGifDrawable = getGifBg(R.drawable.bg_audio_line_from_gif);
            if (mGifDrawable == null) {
                mGifAudioLine.setBackgroundResource(R.drawable.bg_audio_line_from);
            } else {
                mGifAudioLine.setBackgroundDrawable(mGifDrawable);
            }
        }
    }

    /**
     * 停止gif播放
     */
    private void stopGif(){
        if (mGifDrawable == null) {
            return;
        }

        try {
            mGifDrawable.stop();
            mGifDrawable.reset();
            mGifDrawable.seekToFrame(0);
        } catch (Exception e) {

        }
    }

    /**
     *  获取gif 图像
     * @param resId
     * @return
     */
    public GifDrawable getGifBg(int resId){
        try {
            return new GifDrawable(mContext.getResources(), resId);
        } catch (Exception e) {
            return null;
        }
    }
	
	
	/**
	 * @n<b>函数名称</b>     :isAudioFileInvalid
	 * @brief 判断语音文件是否可用，同时设置语音长度
	 * @see
	 * @version  Ver 1.3
	 * @since    
	 * @param  @param audioFilename
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-11-15下午9:52:33      
	*/
	private boolean isAudioFileInvalid(String audioFilename){
		if (TextUtils.isEmpty(audioFilename)){
			return true;
		}
		int duration=mMessage.getDuration();
		if (duration<=0){
			return true;
		}
		return false;
	}
	
	private OnLongClickListener mlistener=new OnLongClickListener() {
		@Override
		public boolean onLongClick(View arg0) {
			MessageLongClickMenuFactory.getInstance().show(mContext,mMessage);
			return false;
		}
	};
	
	private class AudioOnClickListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			int extraFlag=mMessage.getExtraFlag();
			switch (extraFlag) {
			case MessageState.SENDING:
			case MessageState.UPLOADING:
			case MessageState.DOWNLOADING:
				//几个进行中的状态不作任何处理
				return;
			case MessageState.SEND_SUCCESS:
			case MessageState.DOWNLOAD_SUCCESS:
			case MessageState.SEND_FAIL:
			case MessageState.UPLOAD_FAIL:
                if (mGifDrawable.isPlaying()) {
                    stopGif();
                }else{
                    initGifDrawable();
                }

				AudioQuenePlayManager.getInstance().startQuenePlay(mMessage, mContext);
				if (!mMessage.isRead()){
					mMessage.setIsRead(MessageCommonState.DONE,true);	
				}
				break;
			case MessageState.DOWNLOAD_FAIL:
				//下载失败
				if (IMSStateManager.getInstance().isNetworkAvailable()){
					//有网络
					mMessage.doDownload();
				}else{
					ToastUtils.display(mContext, R.string.net_warn_no_network);
				}
				break;
			default:
				break;
			}
		}
	}

	@Override
	public IMessageDisplay getData() {
		return mMessage;
	}
}
